import time
from datetime import datetime
import urllib
import base64
import getpass
from xml.dom.minidom import parse, parseString

def show_cmp(x, y):
    if x['start_time'] < y['start_time']:
        return -1
    elif x['start_time'] > y['start_time']:
        return 1
    else:
        return 0

def getChildData(dom, tag):
    element = dom.getElementsByTagName(tag)
    if element:
        return element[0].childNodes[0].data
    else:
        return ''

def processTVPIFile_XML(tvpis):
    shows = []
    for tvpi in tvpis:
        tvpi_nodes = tvpi.childNodes

        for tvpi_node in tvpi_nodes:
            tvpi_b64 = tvpi_node.data
            tvpi_string = base64.b64decode(tvpi_b64)
            tvpi_xml = parseString(tvpi_string)

            show_dict = {}
            show_dict['rf_channel'] = getChildData(tvpi_xml, 'rf-channel')
            
            start_date = getChildData(tvpi_xml, 'start-date')
            start_time = getChildData(tvpi_xml, 'start-time')

            show_dict['start_time'] = datetime.strptime(
                "%s %s EDT" % (start_date, start_time),
                "%Y%m%d %H:%M %Z" 
            )

            show_dict['duration'] = getChildData(tvpi_xml, 'duration')

            end_time = getChildData(tvpi_xml, 'end-time')
            end_date = getChildData(tvpi_xml, 'end-date')
    
            show_dict['end_time'] = datetime.strptime(
                "%s %s UTC" % (end_date, end_time),
                "%Y%m%d %H:%M %Z"
            )

            show_dict['title'] = getChildData(tvpi_xml, 'program-title')
            show_dict['station'] = getChildData(tvpi_xml, 'station')
            show_dict['episode_title'] = getChildData(tvpi_xml, 'episode-title')
            show_dict['description'] = getChildData(tvpi_xml, 'program-description')

            shows.append(show_dict)

    return shows


def getUUID(userid, password):
    u = urllib.urlopen("http://www.titantv.com/Services/PartnerTools.asmx/GetUUID?PartnerId=49757&ProductId=string&ProductVersion=string&LoginName=%s&Password=%s" % (
        userid,
        password
    ))
    urldata = u.read()
    p = parseString(urldata)
    try:
        uuid = getChildData(p, 'UUID')
    except IndexError:
        print "Authentication Error!"
        return None
    return uuid

def getSchedule(uuid):
    u = urllib.urlopen('http://www.titantv.com/Services/PartnerTools.asmx/RetrieveAllRemote?PartnerId=49757&ProductId=string&ProductVersion=string&UUID=%s' % uuid)
    urldata = u.read()
    p = parseString(urldata)
    tvpifile_tag = p.getElementsByTagName('TVPIFile')
    shows = processTVPIFile_XML(tvpifile_tag)
    shows.sort(show_cmp)
    return shows


def main():
    uuid = None
    while not uuid:
        userid = raw_input("Please enter UID:")
        password = getpass.getpass("Please enter PASSWORD:")
        uuid = getUUID(userid, password)

    print getSchedule(uuid)


if __name__ == "__main__":
    main()

